﻿namespace ChinaUnicom.Tasks
{
    using System;
    using ChinaUnicom.Models;
    using ChinaUnicom.Schedule;

    internal class PackageTask : ITask
    {
        public Package Package { get; private set; }

        public PackageTask()
        {
            Package = new Package();
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.RequestPackageInfo(x =>
            {
                if (x.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var items = Factory.Parser.Parse(x.Result, InfoType.Package);

                    /*客户姓名
                      手机号码
                      套餐名称
                      查询日期
                      起止日期*/

                    foreach (var item in items)
                    {
                        switch (item.Name)
                        {
                            case "套餐名称":
                                Package.Name = item.Value;
                                break;
                            case "查询日期":
                                DateTime occurred;
                                if (DateTime.TryParse(item.Value, out occurred))
                                {
                                    Package.Occurred = occurred;
                                }
                                break;
                            case "起止日期":
                                string[] times = item.Value.Split(new[] { '~' });
                                if (times.Length == 2)
                                {
                                    DateTime started, ended;
                                    if (DateTime.TryParse(times[0], out started))
                                    {
                                        Package.Started = started;
                                    }
                                    if (DateTime.TryParse(times[1], out ended))
                                    {
                                        Package.Ended = ended;
                                    }
                                }
                                break;
                            default:
                                if (item.HasDetails)
                                {
                                    Package.Items.Add(item);
                                }
                                break;
                        }
                    }

                    if (Completed != null)
                    {
                        Completed(this, EventArgs.Empty);
                    }
                }
            });
        }

        public int Pending
        {
            get { return 10; }
        }

        public event EventHandler Completed;


        public event EventHandler Started;
    }
}
